﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebPlatform.FiltersAndSession;

namespace WebPlatform.Controllers
{
    [CustomAuthorize]
    public class FileController : Controller
    {


        public ActionResult Upload(HttpPostedFileBase imgFile, string dir, string localUrl)
        {

            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,mp4,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
            extTable.Add("onlinefile","pdf");


            if (imgFile == null)
            {
                return RedirectToAction("Error", new { message = "请选择文件" });
            }

            string baseDir = "/Upload/";
            string dirPath = Server.MapPath(baseDir);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            if (string.IsNullOrEmpty(dir))
            {
                dir = "image";
            }
            if (!extTable.ContainsKey(dir))
            {
                return RedirectToAction("Error", new { message = "不支持的文件类型" });
            }

            string fileName = imgFile.FileName;
            string fileExt = Path.GetExtension(fileName).ToLower();

            //最大文件大小
            int maxSize = 10240000;
            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                return RedirectToAction("Error", new { message = "文件大小超过限制（10M）" });
            }

            if (string.IsNullOrEmpty(fileExt)
                || Array.IndexOf(((string)extTable[dir]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return RedirectToAction("Error", new { message = "上传文件扩展名是不允许的扩展名。\n只允许" + ((string)extTable[dir]) + "格式。" });
            }

            //创建文件夹
            dirPath += dir + "/";
            string ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            dirPath += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            string newFileName = Guid.NewGuid().ToString() + fileExt;

            string filePath = dirPath + newFileName;

            imgFile.SaveAs(filePath);

            string sourcePath = baseDir + dir + "/" + ymd + "/";

            string fileUrl = string.Empty;

            if (dir == "onlinefile")
            {
                fileUrl = ConvertToSwf(sourcePath, newFileName);
                if (string.IsNullOrEmpty(fileUrl))
                {
                    return RedirectToAction("Error",
                        new { message = "文档转换异常，请确认文档是否为加密文档" });
                }
            }
            else
            {
                fileUrl = sourcePath + newFileName;
            }

            Hashtable hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileUrl;
            return Json(hash, "text/html; charset=UTF-8;", JsonRequestBehavior.AllowGet);
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        string ConvertToSwf(string sourcePath, string fileName)
        {
            var pa = Path.GetExtension(fileName).ToLower();
            var toolPath = string.Empty;
            switch (pa)
            {
                case ".pdf":
                    toolPath = Server.MapPath("~/Scripts/SWFTools/pdf2swf.exe");
                    break;
                case ".gif":
                    toolPath = Server.MapPath("~/Scripts/SWFTools/gif2swf.exe");
                    break;
                case ".jpeg":
                    toolPath = Server.MapPath("~/Scripts/SWFTools/jpeg2swf.exe");
                    break;
                case ".jpg":
                    toolPath = Server.MapPath("~/Scripts/SWFTools/jpeg2swf.exe");
                    break;
                case ".png":
                    toolPath = Server.MapPath("~/Scripts/SWFTools/png2swf.exe");
                    break;
                case ".docx":
                    toolPath = Server.MapPath("~/Scripts/SWFTools/font2swf.exe");
                    break;
                default: break;
            }
            var sourceFile = sourcePath + fileName;
            var targetFile = sourceFile + ".swf";
            try
            {
                using (Process p = new Process())
                {
                    string source = @"""" + Server.MapPath(sourceFile) + @"""";
                    string target = @"""" + Server.MapPath(targetFile) + @"""";
                    //@"""" 四个双引号得到一个双引号，如果你所存放的文件所在文件夹名有空格的话，要在文件名的路径前后加上双引号，才能够成功
                    // -t 源文件的路径
                    // -s 参数化（也就是为pdf2swf.exe 执行添加一些窗外的参数(可省略)）
                    string argsStr = "  -t " + source + " -s flashversion=9 -o " + target;

                    ProcessStartInfo psi = new ProcessStartInfo(toolPath, argsStr);
                    psi.CreateNoWindow = true;
                    psi.ErrorDialog = false;
                    psi.UseShellExecute = true;
                    psi.WindowStyle = ProcessWindowStyle.Hidden;

                    p.StartInfo = psi;
                    p.Start();

                    p.WaitForExit();

                }

                System.IO.File.Delete(Server.MapPath(sourceFile));
            }
            catch (Exception)
            {
                return string.Empty;
            }

            return targetFile;
        }



        /// <summary>
        /// 文件上传错误信息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public ActionResult Error(string message)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            return Json(hash, "text/html; charset=UTF-8;", JsonRequestBehavior.AllowGet);
        }



        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Delete(string filePath)
        {
            var fullPath = Server.MapPath(filePath);
            System.IO.File.Delete(fullPath);
            return Json(true);
        }



        public ActionResult AjaxFileUploader()
        {
            return View();
        }


    }
}
